<template>
  <el-upload
      action="string"
      list-type="picture-card"
      :class="{'hide_box': images.length === limit}"
      class="business-image"
      accept="image/*"
      :before-upload="onBeforeUploadImage"
      :on-preview="handlePictureCardPreview"
      :http-request="uploadImagePic"
      :on-remove="onRemovePic"
      :on-exceed="onExceedPic"
      :limit="limit"
      :multiple="multiple"
      :file-list="images"
  >
    <i class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import Uploader from 'packages/BaseUpload/uploader';
import FormMixin from "@form/mixin/form";
const IMG_TYPE = ['jpg', 'png', 'gif', 'psd', 'tiff', 'bmp', 'jpeg', 'tif'];
export default {
  name: 'form-image',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      images: [],
    }
  },
  computed: {
    limit() {
      return this.field?.setting?.limit || 10;
    },
    multiple() {
      return this.field?.setting?.isMulti || false;
    },
  },
  watch: {
    value: {
      handler(newValue) {
        this.images = newValue || [];
      },
      immediate: true,
    }
  },
  methods: {
    onBeforeUploadImage(file) {
      
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error(this.$t('common.validate.imageLimit', {limit: '10M'}));
      }
      
      const fileSizeLimit = this.field?.setting?.fileSizeLimit
      if (fileSizeLimit) {
        const isLimit = file.size / 1024 / 1024 < fileSizeLimit;
        if (!isLimit) {
          this.$message.error(this.$t('common.validate.imageLimit', { limit: `${fileSizeLimit}M` }));
          return false;
        }
      }
      
      // 图片类型判断
      let isExt = IMG_TYPE.indexOf(this.getExt(file.name)) > -1
      if(!isExt) {
        this.$message.error(this.$t('common.base.uploadModal.tips2'));
      }
      
      return isLt10M && isExt;
    },

    // 返回小写后缀
    getExt(fileName){
      if(!fileName) return '';

      let index = fileName.lastIndexOf('.');
      if(index < 0) return '';

      return fileName.substring(index + 1).toLowerCase();
    },

    // TODO 图片展示后期需要修改
    handlePictureCardPreview(file){
      this.$previewElementImg(file.url);
    },

    uploadImagePic (param) {
      let action = this.field?.action || '/files/upload'
      let actionStorage = this.field?.actionStorage || '/files/remainingStorage'
      let actionOptions = this.field?.actionOptions || {}
      Uploader.upload(param.file, action, {...actionOptions}, actionStorage)
          .then((result) => {
            if (result.status !== 0) {
              this.$message({
                message: `${result.message}`,
                duration: 1500,
                type: 'error',
              });
              return;
            }
            let file = result.data;
            let item = {
              uid: param.file.uid,
              id: file.id,
              filename: file.fileName,
              // 如果后端返回url,必须使用。如果后端不返回，需要拼接
              url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
              fileSize: file.fileSizeStr,
            };
            this.images.push(item);
            this.inputForValue(this.images);
          })
          .catch((err) => {
            console.warn(err);
          })
    },
    onRemovePic(o) {
      if(this.images?.length) {
        this.images = this.images.filter(item => item.id != o.id)
        this.inputForValue(this.images);
      }
    },
    onExceedPic () {
      this.$message.error(`最多上传${this.limit}张图片!`);
    },
  },
}
</script>

<style scoped lang="scss">
.business-image {
  ::v-deep.el-upload-list__item {
    transition: none !important;
  }
  ::v-deep .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
    margin-bottom: 6px;
    &:hover {
      border-color: $color-primary;
    }
  }
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}
.hide_box ::v-deep .el-upload--picture-card {
  display: none;
}
</style>